import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import {message} from 'ant-design-vue'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 300000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = error => {
  setTimeout(() => {
    message.destroy()
  }, 1000);
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }else if (error.response.status === 401) {
      notification.error({
        message: '没有权限',
        description: '授权验证失败'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }else if (error.response.status === 413) {
      notification.error({
        message: '错误',
        description: '文件超出限制'
      })
    }else {
      notification.error({
        message: '错误',
        description: '服务器出错，请稍候重试'
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  const md_id = storage.get('mdId')
  const store_id = storage.get('storeId')
  // if (store_id && store_id > 0) {
  //   config.url = config.url + '&store_id=' + store_id
  // }
  if (md_id && md_id > 0) {
    config.url = config.url + '&md_id=' + md_id
  }

  if (config.storeUseMd) {
    config.url = config.url + '&md_id=-1'
  }

  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use(response => {
  // console.log('sss',response,response.data,typeof(response.data));
  if(response.config.responseType == 'blob'){
    saveBlob(response);
    return response.data;
  }
  const data = response.data
  if (data.code > 0) {
    notification.error({
      message: 'error',
      description: data.msg
    })
  }
  if (data.tips) {
    notification.warning({
      message: '提示',
      description: data.tips
    })
  }
  return data
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

const saveBlob = function(response){
    try{
      let fr = new FileReader();
      fr.onload = function(){
        try{
          let data = JSON.parse(this.result)
          console.log(this.result, data, data.code);
          if (data.code > 0) {
            notification.error({
              message: 'error',
              description: data.msg
            })
          }
          return data
        }catch(err){
          console.log(err);
          let blob = response.data;
          console.log(blob);
          let url = window.URL.createObjectURL(blob);
          let a = document.createElement("a");
          a.href = url;
          if(response.config.method == 'get'){
            a.download = response.config.params._filename;
          }
          if(response.config.method == 'post'){
            a.download = response.config.data._filename;
          }
          a.click();
          return blob;
        }
      };
      fr.readAsText(response.data);
    }catch(err){
      console.log(err);
    }
}

export default request

export { installer as VueAxios, request as axios }
